package software.lib.util;

import org.neo4j.driver.v1.*;
import software.lib.entity.Gig;
import software.lib.entity.graph.Node;

import java.util.stream.Stream;


/**
 * @author sunfiyes 2016年12月12日
 * neo驱动
 */

public class NeoDriver implements AutoCloseable {
	String url = "bolt://localhost";
	String username = "neo4j";
	String password = "neo4j";
	static Driver driver = null;
//	Session session = null;

	public NeoDriver(){
		if(driver==null)
			driver = GraphDatabase.driver(url, AuthTokens.basic(username, password),  Config.build().withEncryptionLevel(Config.EncryptionLevel.NONE).toConfig() );
//		if(session==null)
//			session = driver.session();
	}

	//原因：每个session只能用于一个线程内，将session放在此处是为了可以并行化
	public StatementResult query(String cyper){
		try (Session session = driver.session()){
			return session.run(cyper);
		}
	}
	
	public void close(){
//		session.close();
	}

	public static void main(String[] args){
		try (NeoDriver driver = new NeoDriver()){
			Stream.of(3747,17983,20593,30100,40345,52970).parallel().map(gid -> "MATCH (x:gig{id:\"" +gid+
					"\"}) RETURN ID(x) As id, Labels(x)[0] As type, x.name As name")
					.map(ql -> driver.query(ql).single())
					.map(record -> new Node(record.get("id").asInt(),record.get("type").asString(),record.get("name").asString()))
					.forEach(System.out::println);
		}
	}


}
